<?php
session_start();
//$-POST $_GET: 在后端获取前端页面提交数据的全局数组
$userName = trim($_POST['username']);
$pw = trim($_POST['pw']);
$code = trim($_POST['code']);//获取前端页面的验证码


include_once "conn.php";
//判断验证码是否正确
if(strtolower($_SESSION["captcha"]) == strtolower($code)){
    $_SESSION["captcha"] = '';
}else{
    $_SESSION["captcha"] = '';
    echo "<script>alert('验证码错误');location.href='login.php'</script>";

    exit();
}
//进行数据的验证
if(!strlen($userName)|| !strlen($pw)){
    echo "<script>alert('用户名和密码必须填写');
     history.back()
</script>";
    exit;

}else{
    if(!preg_match('/^[a-zA-Z0-9_]{3,10}$/', $userName)){
        echo "<script>alert('用户名必须填写，且只能大小写字符和数字下划线组成，长度为3~10个字符');
     history.back()
</script>";
        exit;
    }
    if (!preg_match('/^[a-zA-Z0-9_*]{6,10}$/', $pw)) {
        echo "<script>alert('密码必须填写，且只能大小写字符和数字下划线和*组成，长度为6~10个字符two');
     history.back()
</script>";
        exit;
    }
}
//if($pw <> $cpm){
//    echo "<script>alert('密码和确认密码必须相同');
//     history.back()
//</script>";
//    exit;
//}else {

//}
//判断用户名是否重复
$sql ="select * from info where username = '$userName' and pw= '".md5($pw)."'";
$result = mysqli_query($conn, $sql);//返回一个记录表
$num = mysqli_num_rows($result);
if($num){
    $_SESSION['loggedUsername'] = $userName;
    //判断是否为admin
    $info = mysqli_fetch_array($result);//分割info字符串存为数组形式
    if($info['admin']){
        $_SESSION['isAdmin'] = 1;
    }else{
        $_SESSION['isAdmin  '] = 0;
    }
    echo "<script>alert('登入成功');
//     history.back()
location.href='index.php';
</script>";
}else{
//  unset删除登入信息
    unset($_SESSION['loggedUsername']);
    unset($_SESSION['isAdmin']);
    echo "<script>alert('登入失败');
//     history.back()
</script>";
}
//if(!empty($email)){
//    if(!preg_match('/^[a-zA-Z0-9_\-]+@([a-zA-Z0-9]+\.)(com|cn|net|org)$/', $email)){
//        echo "<script>alert('邮箱格式不正确');
//     history.back()
//</script>";
//        exit;
//    }
//}
$sql = "insert into info (username, pw, sex, email, fav, createTime) values ('$userName', '".md5($pw)."', '$sex', '$email', '$fav', '".time()."')";
//执行查询语句

$result = mysqli_query($conn, $sql);
if($result){
    echo "<script>alert('数据插入成功');location.href='index.php'</script>";
}else{
    echo "<script>alert('数据插入失败');</script>";
}


